<?php
	require_once ('config/connection.php');

	$id1='';
	$imap = imap_open('{imap.gmail.com:993/imap/ssl}INBOX','testsynergyquad@gmail.com','synergytest') or die('Cannot connect to mail');
	$message_count = imap_num_msg($imap);
	$result = imap_search($imap, 'UNSEEN');
	
	if($result)
	{ 
		for($j = 0; $j <= count($result); $j++) {
			$email=imap_fetchheader($imap,$result[$j]);
		
			$lines = explode("\n", $email);
		 
		 	$splittingheaders = true;
		 
		 	for ($i=0; $i < count($lines); $i++) {
		 		if ($splittingheaders) {
			 		// this is a header
			 		$headers .= $lines[$i]."\n";
			 
			 		// look out for special headers
			 		if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
			 			$subject = $matches[1];
						$id=explode('#',$subject);
						$id1=$id[1];
						echo $id1;
			 		}
	 
	 			}
	 		}
	
			$structure = imap_fetchstructure($imap, $result[$j]);
	
			// find if if multipart message
			$attachments = array();
			if(isset($structure->parts) && count($structure->parts)) {
			
				for($i = 0; $i < count($structure->parts); $i++) {
			     
					$attachments[$i] = array(
						'is_attachment' => false,
			
						'filename' => '',
						'name' => '',
						'attachment' => ''
					);
					
					if($structure->parts[$i]->ifdparameters) {
			
						foreach($structure->parts[$i]->dparameters as $object) {
			
							if(strtolower($object->attribute) == 'filename') {
								
								$attachments[$i]['is_attachment'] = true;
								$attachments[$i]['filename'] = $object->value;
			
							}
						}
					}
					
					if($structure->parts[$i]->ifparameters) {
						foreach($structure->parts[$i]->parameters as $object) {
							if(strtolower($object->attribute) == 'name') {
								$attachments[$i]['is_attachment'] = true;
			
								$attachments[$i]['name'] = $object->value;
							}
						}
					}
					
					if($attachments[$i]['is_attachment']) {
			
						$attachments[$i]['attachment'] = imap_fetchbody($imap, $message_count, $i+1);
			
						if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
							$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
						}
						elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
			
							$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
						}
					}
				}
			}
	
			for($i = 1; $i < count($attachments); $i++)
			{
				if($attachments[$i]['is_attachment'])
			  	{
					$new_file_name=uniqid("auto").".png";
					$new_file_name1 = "upload_image/".uniqid("auto").".png";
			 		echo $attachments[$i]['filename'];
			
					$handle = fopen($new_file_name1, 'w') or die('Cannot open file:  '.$new_file_name1);
					fwrite($handle,$attachments[$i]['attachment']);
			
					create_thumbnail($new_file_name1,"upload_image/thumps/thump_".$new_file_name,50,40);
					inserinto_database("mservices/upload_image"."/".$new_file_name, "mservices/upload_image"."/thumps/thump_".$new_file_name,$id1);
				}
			}
			imap_mail_move($imap,$j,'test');
		}
	}

	function create_thumbnail($infile,$outfile,$maxw,$maxh,$stretch = FALSE) 
	{
	  clearstatcache();
	  if (!is_file($infile)) {
	    trigger_error("Cannot open file: $infile",E_USER_WARNING);
	    return FALSE;
	  }
	 
	  $functions = array(
	    'image/png' => 'ImageCreateFromPng',
	    'image/jpeg' => 'ImageCreateFromJpeg',
	  );
	 
	  if (function_exists('ImageCreateFromGif')) { $functions['image/gif'] = 'ImageCreateFromGif'; }
	 
	  $size = getimagesize($infile);
	 
	  if (!$function = $functions[$size['mime']]) {
	      trigger_error("MIME Type unsupported: {$size['mime']}",E_USER_WARNING);
	    return FALSE;
	  }
	 
	  if (!$source_img = $function($infile)) {
	      trigger_error("Unable to open source file: $infile",E_USER_WARNING);
	    return FALSE;
	  }
	 
	  $save_function = "image" . strtolower(substr(strrchr($size['mime'],'/'),1));
	 
	  list($neww,$newh) = scale_dimensions($size[0],$size[1],$maxw,$maxh,$stretch);
	 
	  if ($size['mime'] == 'image/png') {
	    $temp_img = imagecreatefrompng($infile);
	    if (imagecolorstotal($temp_img) != 0) {
	      $indexed_png = TRUE;
	    } else {
	      $indexed_png = FALSE;
	    }
	    imagedestroy($temp_img);
	  }
	 
	  if ($size['mime'] == 'image/gif' || ($size['mime'] == 'image/png' && $indexed_png)) {
	    $new_img = imagecreate($neww,$newh);
	    imagepalettecopy($new_img,$source_img);
	 
	    $color_transparent = imagecolortransparent($source_img);
	    if ($color_transparent >= 0) {
	      imagefill($new_img,0,0,$color_transparent);
	      imagecolortransparent($new_img, $color_transparent);
	    }
	  } else {
	    $new_img = imagecreatetruecolor($neww,$newh);
	  }
	 
	  imagecopyresampled($new_img,$source_img,0,0,0,0,$neww,$newh,$size[0],$size[1]);
	 
	  if ($save_function == 'imagejpeg') {
	      if (!$save_function($new_img,$outfile,75)) {
	          trigger_error("Unable to save output image",E_USER_WARNING);
	          return FALSE;
	      }
	  } else {
	      if (!$save_function($new_img,$outfile)) {
	          trigger_error("Unable to save output image",E_USER_WARNING);
	          return FALSE;
	      }
	  }
	 
	  imagedestroy($source_img);
	  imagedestroy($new_img);
	 
	  return TRUE;
	}

	function scale_dimensions($w,$h,$maxw,$maxh,$stretch = FALSE) {
	    if (!$maxw && $maxh) {
	      $newh = $maxh;
	      if ($h < $maxh && !$stretch) { $newh = $h; }
	      else { $newh = $maxh; }
	      $neww = ($w * $newh / $h);
	    } elseif (!$maxh && $maxw) {
	      if ($w < $maxw && !$stretch) { $neww = $w; }
	      else { $neww = $maxw; }
	      $newh = ($h * $neww / $w);
	    } elseif (!$maxw && !$maxh) {
	      return array($w,$h);
	    } else {
	      if ($w / $maxw > $h / $maxh) {
	        if ($w < $maxw && !$stretch) { $neww = $w; }
	        else { $neww = $maxw; }
	        $newh = ($h * $neww / $w);
	      } elseif ($w / $maxw <= $h / $maxh) {
	        if ($h < $maxh && !$stretch) { $newh = $h; }
	        else { $newh = $maxh; }
	        $neww = ($w * $newh / $h);
	      }
	    }
	    return array(round($neww),round($newh));
	}

	function inserinto_database($filestr, $thumpstr, $vehID)
	{
		$my_insert = "INSERT INTO vehicle_image (  `image_url` , `vehicle_id`, `thump_url`  ) VALUES ('".$filestr. "',".$vehID.",'" .$thumpstr. "')";
		$my_insert = mysql_query($my_insert) or die("Query ERROR");
	}

    imap_close($imap);
?>
<script type="text/javascript">
	window.opener = 'Self';
    window.open('','_parent','');
    window.close();
</script>